/*
 * Copyright (c) 2017. Xi'an iRain IOT Technology service CO., Ltd (ShenZhen). All Rights Reserved.
 */

package com.parkingwang.keyboard.view;

import com.parkingwang.keyboard.engine.KeyEntry;
import com.parkingwang.keyboard.engine.KeyType;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.render.Canvas;
import ohos.agp.utils.Color;
import ohos.app.Context;

/**
 * @author 黄浩杭 (huanghaohang@parkingwang.com)
 * @since 2017-09-26 0.1
 */
public final class KeyRowLayout extends DirectionalLayout implements Component.DrawTask, Component.EstimateSizeListener {
    private static final float GENERAL_WIDTH_RATE = 0.088f;
    private static final float FUNC_WIDTH_RATE = 0.142f;
    private static final float OTHER_WIDTH_RATE = 0.162f;
    private static final int KEY_HEIGHT = 135;
    /**
     * 单行最大键数达到这个数，则显示窄间隔
     */
    private static final int NARROW_SPACE_KEY_COUNT = 10;
    private static final String TAG = KeyRowLayout.class.getSimpleName();

    private static final float RATIO_FUN_CONFIRM = 5.0f / 8;

    private int mGeneralKeySpace;
    private int mFunKeySpace;

    private int mMaxColumn;
    private int mFunKeyIndex;
    private int mWidthUnused;

    private int mFunKeyCount;

    public KeyRowLayout(Context context) {
        super(context);
        addDrawTask(this);
        setEstimateSizeListener(this);
        setOrientation(DirectionalLayout.HORIZONTAL);
        setClipEnabled(false);
    }

    public void setMaxColumn(int maxColumn) {
        mMaxColumn = maxColumn;
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setRgbColor(RgbColor.fromArgbInt(Color.TRANSPARENT.getValue()));
    }

    public void setFunKeyCount(int funKeyCount) {
        mFunKeyCount = funKeyCount;
    }

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int width = MeasureSpec.getSize(widthMeasureSpec);
        final int childCount = getChildCount();

        // 确定（不含间隔）：10个键的情况下，3个键的宽度+1个间隔的 5/8
        final int functionKeyWidth = (int) (((width - 9 * mGeneralKeySpace) * 3 / 10 + mGeneralKeySpace)
                * RATIO_FUN_CONFIRM);
        final float generalKeyWidth = getGeneralKeyWidth(width, functionKeyWidth);
        // ------------------------------计算控件占用总长度，计算divider值--------------------------------------
        int widthUsed = 0;
        mFunKeyIndex = 0;
        for (int i = 0; i < childCount; i++) {
            Component view = getComponentAt(i);
            if (!(view instanceof KeyView)) {
                continue;
            }
            KeyView keyView = (KeyView) view;

            KeyEntry keyEntry = keyView.getBoundKey();
            ComponentContainer.LayoutConfig params = keyView.getLayoutConfig();
            if (keyEntry.keyType == KeyType.GENERAL) {
                params.width = (int) generalKeyWidth;
            } else {
                params.width = functionKeyWidth;
                if (mFunKeyIndex == 0) {
                    mFunKeyIndex = i;
                }
            }
            widthUsed += params.width + mGeneralKeySpace;
        }

        widthUsed -= mGeneralKeySpace;
        mWidthUnused = width - widthUsed;
        if (mFunKeyCount > 0) {
            setPadding(0, 0, 0, 0);
        } else {
            //此处计算有问题，会导致键盘抖动，现改为0， 正常应为 int padding = mWidthUnused / 2
            setPadding(0, getPaddingTop(), 0, getPaddingBottom());
        }
    }

    private float getGeneralKeyWidth(int width, int functionKeyWidth) {
        float generalKeyWidth = (width - (mMaxColumn - 1) * mGeneralKeySpace) / (mMaxColumn * 1.0f);
        int funKeyWidthUsed = 0;
        if (mFunKeyCount > 0) {
            funKeyWidthUsed = functionKeyWidth * mFunKeyCount + mFunKeySpace * (mFunKeyCount - 1) + mGeneralKeySpace;
        }
        int generalKeyCount = getChildCount() - mFunKeyCount;
        float availableGeneralKeyWidth = width - funKeyWidthUsed - (generalKeyCount - 1) * mGeneralKeySpace;
        if (availableGeneralKeyWidth < generalKeyWidth * generalKeyCount) {
            generalKeyWidth = availableGeneralKeyWidth / generalKeyCount;
        }
        return generalKeyWidth;
    }

    KeyboardView mKeyBoardView;

    public void setKeyBoardView(KeyboardView keyBoardView) {
        mKeyBoardView = keyBoardView;
    }

    //这里根据文字按键控制按键大小，比例是根据文字按键进行计算
    @Override
    public void onDraw(Component component, Canvas canvas) {
        int width = mKeyBoardView.getWidth();
        setWidth(width);
        int allWidth = 0;
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            KeyView keyView = (KeyView) getComponentAt(i);
            if (keyView.getBoundKey().keyType == KeyType.GENERAL) {
                keyView.setWidth((int) (width * GENERAL_WIDTH_RATE));
            } else if (keyView.getBoundKey().keyType == KeyType.FUNC_DELETE) {
                keyView.setWidth((int) (width * FUNC_WIDTH_RATE));
            } else {
                keyView.setWidth((int) (width * OTHER_WIDTH_RATE));
            }
            keyView.setHeight(KEY_HEIGHT);
            int addWidth = keyView.getWidth();
            allWidth += addWidth;
        }
        int margin = ((width - allWidth) - getPaddingLeft() - getPaddingRight()) / (childCount + 2);
        for (int i = 0; i < childCount; i++) {
            KeyView keyView = (KeyView) getComponentAt(i);
            keyView.setMarginLeft(margin);
        }
    }

    @Override
    public boolean onEstimateSize(int i, int i1) {
        onMeasure(i, i1);
        return false;
    }
}